import React, { useEffect, useState } from "react";
import backImg from '../../assets/bg05.jpg'
import {Input,Button,message} from 'antd'
import request from '../../utils/request'
import {useHistory} from 'react-router-dom'
import "../../lib/canvas-nest.min.js";
import "./login.css";

const Login = ()=>{
  let user_name:string = "admin";
  let user_psd:string = "admin";
  let [code,setCode] = useState("");
  let [appKey,setAppKey] = useState();
  let [captchatImg,setCaptchatImg] = useState();
  const history = useHistory();
  const clickLogin =  async()=>{
    console.log(123);
    var res = await request.main({
      url:"/login",
      methods:"POST",
      data:{
        user_name:user_name,
        user_psd:user_psd,
      }
    })
    console.log(res);
    if(res.code == 200){
      const {token,phone,realName,id} = res.data;
      window.localStorage.setItem("token",token);
      window.localStorage.setItem('user',JSON.stringify({
        phone,realName,id
      }))
      document.getElementsByTagName("canvas")[0].removeAttribute("class");
      history.push("/")
    }else{
      message.error(res.message);
      setCode("");
      getCaptchatImg();
    }
  }

  const getCaptchatImg = async()=>{
    let res = await request.main({
      url:"/login",
      methods:"POST",
      data:{
        user_name:user_name,
        user_psd:user_psd,
      }
    });
    setCaptchatImg(res.data.code);
    setAppKey(res.data.key);
  }

  useEffect(()=>{
    document.getElementsByTagName("canvas")[0].className = "index_bg";
    //获取图片验证码
    // getCaptchatImg();
  },[setCaptchatImg,setAppKey])

  return(
    <div
      style={{
        backgroundImage:`url(${backImg})`,
        height:"100%",
        display:"flex",
        justifyContent:"center",
        alignItems:"center",
        zIndex:-1,
      }}
      >
      <div 
        style={{
          position:"relative",
          width:"300px",
          background: 'rgba(255, 255, 255, 1)',
          padding:"30px",
          borderRadius:"10px",
          display:"flex",
          flexDirection:"column",
          alignItems:"center",
          zIndex:99,
        }}>
        <h4>WELCOME</h4>  
        <Input placeholder="用户名" value={user_name} onChange={(e)=>{user_name=e.target.value}}  />
        <Input placeholder="密码" value={user_psd} onChange={(e)=>{user_psd=e.target.value}} type="password" style={{marginTop:"10px",marginBottom:"10px"}} />
        {/* <div style={{display:"flex"}}>
          <Input placeholder="图片验证码" value={code} onChange={(e)=>{setCode(e.target.value)}}  />
          <img src={captchatImg} />
        </div> */}
        <Button style={{marginTop:"20px"}} type="primary" onClick={clickLogin}>登录</Button>
      </div>
    </div>
  )
  
}

export default Login;